"use client";
import React, { useState } from "react";
import {
  Form,
  Input,
  Button,
  Select,
  Upload,
  message,
  Switch,
  Divider,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useRouter } from "next/navigation";
import Head from "next/head";
import withAuth from "@/utils/withAuth";
const { Option } = Select;
const { TextArea } = Input;

interface ArticleForm {
  title: string;
  content: string;
  tags: string[];
  category: string;
  coverImage?: string;
  isPublished: boolean;
}

const PublishPage: React.FC = () => {
  console.log("PublishPage");
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  // 文章分类选项
  const categories = [
    { id: "1", name: "技术" },
    { id: "2", name: "生活" },
    { id: "3", name: "教程" },
    { id: "4", name: "资讯" },
  ];

  // 处理提交
  const handleSubmit = async (values: ArticleForm) => {
    try {
      setLoading(true);
      console.log("提交的表单数据:", values);

      // 这里添加发送到后端API的逻辑
      // const response = await fetch('/api/articles', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify(values),
      // });

      message.success("文章发布成功！");
      router.push("/articles"); // 发布后跳转到文章列表页
    } catch (error) {
      console.error("发布失败:", error);
      message.error("发布失败，请稍后重试");
    } finally {
      setLoading(false);
    }
  };

  // 上传前验证图片
  const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("只能上传JPG/PNG格式的图片！");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片大小不能超过2MB！");
    }
    return isJpgOrPng && isLt2M;
  };

  return (
    <>
      <Head>
        <title>发布文章 - 我的博客</title>
      </Head>

      <div className="max-w-5xl mx-auto px-4 py-8">
        <h1 className="text-2xl text-black  mb-6">发布新文章</h1>

        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{ isPublished: true, tags: [] }}
          className="bg-white p-6 rounded-lg shadow-md custom-form-padding"
        >
          {/* 标题 */}
          <Form.Item
            name="title"
            label="文章标题"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input placeholder="请输入文章标题" className="text-lg" />
          </Form.Item>

          {/* 文章内容 */}
          <Form.Item
            name="content"
            label="文章内容"
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            <TextArea
              placeholder="请输入文章内容..."
              autoSize={{ minRows: 8, maxRows: 20 }}
              className="h-64"
            />
          </Form.Item>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 分类 */}
            <Form.Item
              name="category"
              label="文章分类"
              rules={[{ required: true, message: "请选择文章分类" }]}
            >
              <Select placeholder="请选择文章分类">
                {categories.map((category) => (
                  <Option key={category.id} value={category.id}>
                    {category.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            {/* 标签 */}
            <Form.Item name="tags" label="文章标签">
              <Select
                mode="tags"
                placeholder="输入标签后按回车添加"
                style={{ width: "100%" }}
              >
                <Option value="前端">前端</Option>
                <Option value="后端">后端</Option>
                <Option value="React">React</Option>
                <Option value="Next.js">Next.js</Option>
              </Select>
            </Form.Item>
          </div>

          {/* 封面图片 */}
          <Form.Item name="coverImage" label="封面图片">
            <Upload
              name="coverImage"
              listType="picture-card"
              maxCount={1}
              beforeUpload={beforeUpload}
              // action="/api/upload" // 真实的上传接口
            >
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传图片</div>
              </div>
            </Upload>
          </Form.Item>

          {/* 发布开关 */}
          <Form.Item
            name="isPublished"
            label="立即发布"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Divider />

          <div className="flex justify-end space-x-4">
            <Button onClick={() => router.back()}>取消</Button>
            <Button onClick={() => form.resetFields()}>重置</Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              className="bg-blue-500"
            >
              发布文章
            </Button>
          </div>
        </Form>
      </div>
    </>
  );
};

export default withAuth(PublishPage);
